<template>
   <van-loading type="spinner" size="20" v-if="isLoading" />
  <van-icon
    v-else
    :color="articleAttitude===1 ? '#3296fa':'#777'"
    :name="articleAttitude===1 ? 'good-job':'good-job-o'"
    @click="LikeClick"
  />
</template>

<script>
import { mapGetters } from 'vuex'
import { addLike,deleteLike } from '@/api/article'
  export default {
    data() {
      return {
        isLoading: false  // 节流阀
      }
    },
    computed: {
      ...mapGetters(['haslogin'])
    },
    model:{  // 修改v-model 默认的属性 value 和事件名 input  让名称更加语义化
      prop:'articleAttitude',
      event:'updateAttitude'
    },
    props: {
      //  文章态度
      articleAttitude: {
        type: Number,
        require:true 
      },
      // 文章ID
      articleId:{
        type:[Number,String,Object],
        require:true
      }
    },
    methods: {
      // 点赞 取消 点赞
      async LikeClick() {
        if(!this.haslogin) return this.$toast.fail('登录后再点赞')
        // 1.发请求
        this.isLoading = true
        try {
          // 2. 判断行为
          if(this.articleAttitude===1){
            //点赞了，要取消
            await deleteLike(this.articleId)
            this.$toast.success('取消成功')
          }else{
            //没点赞，要点赞
            await addLike(this.articleId)
            this.$toast.success('点赞成功')
          }
          // 3. 更新视图
          let attitude = this.articleAttitude === 1 ? 0 : 1
          this.$emit('updateAttitude',attitude)
        } catch (error) {
          this.$toast.fail('点赞失败')
        }
        this.isLoading = false
      }
    },
  }
</script>

<style lang="less" scoped>

</style>